# -*- coding: <encoding name> -*-
"""
@Author：mengying
@file： myProcessLog.py
@date：2023/6/14 17:11
@email: 652044581@qq.com
@desc: 过程日志
"""
from utils.myLog import SeqLog
from sanic.response.types import JSONResponse
import time

logger = SeqLog().get_logger()


class ProcessLog(object):

    def __init__(self, request, response=None, exception=None):
        self.request = request
        self.response = response
        self.exception = exception

    def action(self):
        if not self.response:
            self.request.headers['my-duration'] = time.time()
            if self.request.method == "POST":
                if self.request.content_type == 'application/json':
                    self.info(self.request.id.hex, self.request.path, self.request.method, self.request.json)
                else:
                    self.info(self.request.id.hex, self.request.path, self.request.method, self.request.form)
            else:
                self.info(self.request.id.hex, self.request.path, self.request.method, self.request.args)
        else:
            if isinstance(self.response, JSONResponse):
                duration = time.time() - self.request.headers['my-duration']
                self.response.headers['my-log'] = self.request.id.hex
                self.response.headers['my-duration'] = duration
                self.info(self.request.id.hex, self.request.path, self.request.method, self.response.raw_body, duration)

    def info(self, uid, path, method, data, duration=None):

        request_info = {'链路id': uid, "接口": path, "方式": method, '数据:': data}
        if duration:
            request_info.update({'接口耗时:': duration})

        logger.info(str(request_info))